package com.exercise.blog.module.main.controller;/**
 * Created by kete on 2017-05-05.
 */

import com.exercise.blog.module.main.service.UserInfoTestService;
import com.exercise.module.common.dao.entity.BlogUser;
import com.exercise.module.common.mq.MqListener;
import com.exercise.module.common.mq.MqService;
import com.exercise.serlvet.controller.BaseController;
import com.exercise.utils.ExerciseInfo;
import com.exercise.utils.JsonBean;
import com.exercise.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.TextMessage;

/**
 * 作者：kete
 * 创建时间：2017-05-05 14:38
 * 功能描述：
 * 版本：
 */
@Controller
@RequestMapping("/user")
public class UserInfoTestController extends BaseController{

    private static Logger logger = LoggerFactory.getLogger(UserInfoTestController.class);

    @Autowired
    UserInfoTestService userInfoTestService;

    @Autowired
    MqService mqService;

    @Autowired
    ExerciseInfo exerciseInfo;

    @RequestMapping("/index")
    public String index(ModelMap model,Integer id){
        BlogUser user = new BlogUser();

        user.setUsername("xiaoqiang");

        model.put("user",user);
        model.put("exerciseInfo",exerciseInfo);

        return "blog/main/index";
    }


    @RequestMapping("/getUser")
    public String getUser(ModelMap model,Integer id){
        BlogUser user = userInfoTestService.getUser(id);

        model.put("user",user);

        return "blog/main/index";
    }

    @RequestMapping("/sendInfo")
    @ResponseBody
    public JsonBean sendInfo(){
        logger.info("发送消息");
        JsonBean jsonBean = new JsonBean();
        BlogUser user = new BlogUser();

        user.setUsername("xiaoqiang");

        String message = JsonUtils.toJSon(user);

        mqService.send("userInfo",message);

        jsonBean.setCode(1);
        return jsonBean;

    }

    @RequestMapping("/receive")
    @ResponseBody
    public JsonBean receive(){
        logger.info("接受消息");
        JsonBean jsonBean = new JsonBean();

        mqService.subscribe("userInfo", new MqListener() {
            @Override
            public void onMessage(Message message) {
                logger.info("接受消息-success");
                try {
                    TextMessage tm = (TextMessage) message;
                    String msg = tm.getText();

                    BlogUser user = JsonUtils.toBean(msg,BlogUser.class);

                    logger.info(user.toString());
                } catch (JMSException e) {
                    e.printStackTrace();
                }
            }
        });

        jsonBean.setMessage("接受成功");
        return jsonBean;
    }
}
